package com.yln.watcher;

import com.yln.watcher.client.ZkClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
public class TasksChildrenWatcher implements Watcher {

    private final ZkClient zkClient;

    @Override
    public void process(WatchedEvent event) {
        Event.EventType eventType = event.getType();
        log.info("/tasks children watcher triggered. eventType: {}", eventType);
        switch (eventType) {
            case NodeChildrenChanged:
                List<String> addedTasks = zkClient.findAllTasks();
                log.info("/tasks children: {}", addedTasks);
                List<String> cacheTasks = zkClient.getCacheTasks();
                log.info("cached tasks: {}", cacheTasks);
                addedTasks.removeAll(cacheTasks);
                log.info("new added tasks: {}", addedTasks);
                zkClient.randomAssignTask(addedTasks);
                break;
            default:
                break;
        }
    }
}
